// 导入数据库操作模块
const db = require('../db/index')
const path = require("path");
const ss=require('socket.io-stream')
const fs=require('fs')
module.exports = function (io) {
    let socketUsersObj = {}
    let member = 0
    let usersInfo = []

    io.on('connection', function (socket) {
        // 获取一对一消息
        socket.on('couple', data => {
            let user = data
            // console.log(user)
            let coupleIdsList=[socketUsersObj[user.name],socketUsersObj[user.loverName]]
            const sql='INSERT INTO bs_chats SET ?'
            db.query(sql, {
                ...user
            },(err,result)=>{
                if(err) throw err
                if (result.affectedRows !== 1) return res.cc('失败，请稍后再试！')
                // 成功
                io.sockets.to(coupleIdsList).emit("couple", user);
            })
            // io.sockets.to(coupleIdsList).emit("couple", user);

        })

        // 获取用户刚进入聊天界面的唯一socket.io值
        socket.on('selfInfo', (myName,loverName) => {
            socketUsersObj[myName] = socket.id
            // 获取对象所有属性名的数组
            const keys = Object.keys(socketUsersObj)
            // console.log('keys',keys)
            for (let i = 0; i < keys.length; i++) {
                if (keys[i]===loverName) {
                    let coupleIdsList=[socketUsersObj[myName],socketUsersObj[loverName]]
                    io.to(coupleIdsList).emit('selfInfo', true)
                }else {
                    io.to(socketUsersObj[myName]).emit('selfInfo', false)
                }
            }
        })

        socket.on('userLogout', loverName => {
            io.to(socketUsersObj[loverName]).emit('selfInfo', false)
        })


        // 语音测试
        socket.on('message', data => {
            console.log(data)
            member++
            // 给客户端发送消息（发布welcome事件）
            io.emit("welcome", data);

        })

        socket.on('voice', data => {
            console.log(data)
            // member++
            // // 给客户端发送消息（发布welcome事件）
            // io.emit("welcome", data);

        })

    })
    io.on('disconnection', function (socket) {
        console.log('socketUsersObj',socketUsersObj)
        if (socketUsersObj.hasOwnProperty(socket.name)) {
            delete socketUsersObj[socket.name]
            for (let i = 0; i < usersInfo.length; i++) {
                if (usersInfo[i].name == socket.name) {
                    usersInfo.splice(i, 1)
                }
            }
        }
        io.emit('quit', socket.name, usersInfo)
    })
}
